// This is the simplest http server

#include <iostream>

// https://github.com/yhirose/cpp-httplib
#include "../httplib/httplib.h"

using namespace std;

// 2b. Declare a function to response for "/hello"
void OnHello(const httplib::Request& reqeust, httplib::Response& response);
void OnHome(const httplib::Request& reqeust, httplib::Response& response);
void OnImage1(const httplib::Request& reqeust, httplib::Response& response);

int main()
{
    // 1. Create the http server
    httplib::Server httpSrv;

    // 2a. Define a http get response
    httpSrv.Get("/hello", OnHello);
    httpSrv.Get("/", OnHome);
    httpSrv.Get("/image/1.jpg", OnImage1);

    // 3. Start to listen request
    httpSrv.listen("127.0.0.1", 8080);

    return 0;
}

// 2c. Implement function OnHello
void OnHello(const httplib::Request& reqeust, httplib::Response& response)
{
    response.set_content("Hello HTTP Server!", "text/plain");
}

void OnHome(const httplib::Request& reqeust, httplib::Response& response)
{
    // 1. read file Home.htm
    ifstream fsHomeHtml("..\\A1Hello\\Home.htm", ios_base::in);
    // 2. check if okay
    if (!fsHomeHtml.good()) {
        response.status = 404;
        response.set_content("无法打开文件", "text/plain; charset=utf-8");
        return;
    }

    stringstream ss;
    ss << fsHomeHtml.rdbuf();
    response.set_content(ss.str(), "text/html");
}

void OnImage1(const httplib::Request& reqeust, httplib::Response& response)
{
    // 1. read jpg file
    ifstream fsHomeHtml("..\\A1Hello\\Planet-Earth.jpg", ios_base::in|ios_base::binary);
    // 2. check if okay
    if (!fsHomeHtml.good()) {
        response.status = 404;
        response.set_content("无法打开文件", "text/plain; charset=utf-8");
        return;
    }

    stringstream ss;
    ss << fsHomeHtml.rdbuf();
    response.set_content(ss.str(), "image/jpeg");
}